package com.kmu.kmucampus.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import com.kmu.kmucampus.R;
import java.util.List;
import mytest.ssw.www.api.ActionCallbackListener;
import mytest.ssw.www.api.SqliteTools;
import mytest.ssw.www.core.sqLiteTools;
import mytest.ssw.www.mylibrary.DeptNode;


public class LoginActivity extends KBaseActivity {
    ProgressDialog progressDialog;
    EditText accountEdi;//账号editext
    EditText passwordEdi;//密码editext
    CheckBox cb_remPwd;
    CheckBox cb_AutoLogin;
    private SharedPreferences sp;
    SharedPreferences.Editor spEitor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
        Toast.makeText(LoginActivity.this, getFilesDir().toString(), Toast.LENGTH_SHORT).show();
        setContentView(R.layout.activity_login);
        Init();
        if(sp.getBoolean("everUsed",false)==false)
        {
            sqLiteTools st= new sqLiteTools(getFilesDir().toString());
            if(st.initSelectCursor("TB_STU",null).getCount()!=0) st.cleanTB("TB_STU");
            spEitor.clear();
            spEitor.commit();
            spEitor.putBoolean("everUsed", true);
            spEitor.commit();
        }
        if(putLoginInfo())   autoLogin(accountEdi,passwordEdi);
    }

    public void Init() {    //
        sp = getSharedPreferences("KMUCampusLogInfo", Context.MODE_PRIVATE);
        spEitor = sp.edit();
        accountEdi = (EditText) findViewById(R.id.AccountEdi);
        passwordEdi= (EditText) findViewById(R.id.PasswordEdi);
        cb_remPwd = (CheckBox) findViewById(R.id.cb_remPwd);
        cb_AutoLogin=(CheckBox) findViewById(R.id.cb_autoLogin);
        View.OnKeyListener onKey=new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                // TODO Auto-generated method stub
                if(keyCode == KeyEvent.KEYCODE_ENTER){
                    InputMethodManager imm = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    if(imm.isActive()){
                        imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0 );
                        String  account= accountEdi.getText().toString();
                        String password= passwordEdi.getText().toString();
                        Login(account, password);
                    }
                    return true;
                }
                return false;
            }
        };
        passwordEdi.setOnKeyListener(onKey);
        accountEdi.setOnKeyListener(onKey);
    }
    public boolean putLoginInfo(){
        boolean canAutoLogin=false;
        Log.d("putLoginInfo", "false");
        if(sp.getString("account", null)!=null)
        {  Log.d("putLoginInfo","setAccount:"+sp.getString("account", ""));
            Log.d("putLoginInfo","password:"+sp.getString("password", null)+"isRempPass:"+Boolean.toString(sp.getBoolean("isRemPwd", false)));
            accountEdi.setText(sp.getString("account", ""));
            if (sp.getString("password", null) != null && sp.getBoolean("isRemPwd",false)==true)
            {
                Log.d("putLoginInfo", "setPassword");
                cb_remPwd.setChecked(true);
                passwordEdi.setText(sp.getString("password",null));
                     if(sp.getBoolean("isAutoLogin", false) != false)
                     {   Log.d("putLoginInfo", "true");
                         cb_AutoLogin.setChecked(true);
                         if(sp.getBoolean("lastLoginSucc",false))
                            canAutoLogin=true;
                     }

                }
        }
        return canAutoLogin;
    }
        public void autoLogin(EditText et_account,EditText et_password){
            if(appAction.getNetworkInfo(getApplicationContext())!=null) {
                        if (sp.getString("account", null) != null) {
                            if (sp.getBoolean("isAutoLogin", false) != false) {
                                if (sp.getBoolean("lastLoginSucc", false) == true)
                                    EnterMainactivity(sp.getString("account", null));
                            }
                        }

            }
        }
    public void LoginBt(View v) {
       String  account= accountEdi.getText().toString();
        String password= passwordEdi.getText().toString();
        Login(account, password);
    }

    private void putSharePrefrence(boolean flag)
    {
        boolean isAutoLogin=cb_AutoLogin.isChecked();
        boolean isRemPwd=cb_remPwd.isChecked();
        String account=accountEdi.getText().toString();
        String password=passwordEdi.getText().toString();
        spEitor.putBoolean("isRemPwd", isRemPwd);
        spEitor.putBoolean("isAutoLogin", isAutoLogin);
        spEitor.putBoolean("lastLoginSucc", flag);
        Log.d("putSharePrefrence", "" + flag);

        if(flag==true) {
            spEitor.putString("account", account);
            spEitor.putString("password", password);
            Log.d("putSharePrefrenceFlag", "password:" + password);
            spEitor.commit();
        }
        boolean isSucc=spEitor.commit();
        Log.d("putSharePrefrence:" + isSucc, "password:" + sp.getString("password", null));

    }

    public void Login(final String accountnum,String password) {
        progressDialog=new ProgressDialog(LoginActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setTitle("登陆");
        progressDialog.setMessage("正在登陆....");
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(true);
        progressDialog.setButton("取消", new Bt1DialogListener());
        progressDialog.show();
        if(sp.getString(accountnum,null)!=null && appAction.getNetworkInfo(getApplicationContext())==null)
        {EnterMainactivity(accountnum);}
          else {
            appAction.login(accountnum, password, new ActionCallbackListener<Void>() {
                @Override
                public void onSuccess(Void data) {
                    //进入主页
                    EnterMainactivity(accountnum);
                    //写入SharePrefrence
                    putSharePrefrence(true);
                    Log.d(" appAction.login", "enter");

                    Toast.makeText(LoginActivity.this, accountnum + "登录成功", Toast.LENGTH_SHORT).show();
                    progressDialog.dismiss();
                }

                @Override
                public void onFailure(String errorEvent, String element) {
                    // EnterMainactivity();//测试使用，登陆失败仍然可以进入
                    progressDialog.dismiss();
                    putSharePrefrence(false);
                    spEitor.commit();
                    Toast.makeText(LoginActivity.this, errorEvent, Toast.LENGTH_SHORT).show();
                }
            });
        }


    }

    public void EnterMainactivity(String data) {
        final SqliteTools sqlTool=new SqliteTools(getFilesDir().toString());
        List<DeptNode> deptList = sqlTool.getDeptfoFrDB("TB_DEPT");
        if(deptList.size() > 33)
        {
            Log.i("initDept","clean Table");
              sqlTool.cleanTB(TB_DEPT);
        }
        initDept();
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        intent.putExtra("account", data);    // intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        startActivity(intent);
        this.finish();


    }
    class Bt1DialogListener implements DialogInterface.OnClickListener {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // 点击“确定”按钮取消对话框
            dialog.cancel();
        }
    }
    public void initDept() {
        // String CONNECT_TYPE = appAction.getNetworkInfo(this);
        final  SqliteTools sqlTool=new SqliteTools(getFilesDir().toString());
        Log.d("initDept_fileDir",""+getFilesDir().toString()+TB_DEPT);
        List<DeptNode> deptList = sqlTool.getDeptfoFrDB(TB_DEPT);
        Log.d("DeptNodeSizeFromDB",""+deptList.size());
        if ( deptList.size() == 0) {
            Log.d("DeptNodeSizeFromNet",""+deptList.size());
            appAction.GetDeptNodeList(new ActionCallbackListener<List<DeptNode>>() {
                @Override
                public void onSuccess(List<DeptNode> data) {
                    sqlTool.insertDetp(TB_DEPT, data);
                    List<DeptNode> deptList = sqlTool.getDeptfoFrDB(TB_DEPT);
                    Log.d("DeptNodeCount",""+deptList.size());
                }

                @Override
                public void onFailure(String errorEvent, String element) {
                    //     progressDialog.dismiss();
                    Toast.makeText(LoginActivity.this, errorEvent, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }



}



/*
    private void listRecentTasks() throws PackageManager.NameNotFoundException {
        ActivityManager mgr = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RecentTaskInfo> tasks = mgr.getRecentTasks(20, 0);
        String packagename;
        String label;
        for(ActivityManager.RecentTaskInfo task: tasks){
            packagename = task.baseIntent.getComponent().getPackageName();
            label = getPackageManager().getApplicationLabel(getPackageManager().getApplicationInfo(packagename, PackageManager.GET_META_DATA)).toString();
            Log.v("listRecentTasks", packagename + ":" + label);
        }
    }

  private void listTasks() throws PackageManager.NameNotFoundException {
        ActivityManager mgr = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.AppTask>  tasks = mgr.getAppTasks();
        String packagename;
        String label;
        for (ActivityManager.AppTask task: tasks){
            packagename = task.getTaskInfo().baseIntent.getComponent().getPackageName();
            label = getPackageManager().getApplicationLabel(getPackageManager().getApplicationInfo(packagename, PackageManager.GET_META_DATA)).toString();
            Log.v("listTasks",packagename + ":" + label);
        }
    }
* */